<?php
$cs = Yii::app()->clientScript;
$cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/CodeMirror/js/codemirror.js');

$script = "
var editor = CodeMirror.fromTextArea('".CHtml::getActiveId($model->currentRevision, 'html')."', {
    height: '350px',
    parserfile: 'parsexml.js',
    stylesheet: '".Yii::app()->theme->baseUrl."/scripts/CodeMirror/css/xmlcolors.css',
    path: '".Yii::app()->theme->baseUrl."/scripts/CodeMirror/js/',
    continuousScanning: 500,
    lineNumbers: true
});
";
$cs->registerScript(__CLASS__.'#InitXMLEditor', $script);
$script = "
jQuery('#same_revision').change(function(){
    var new_revision_notify = jQuery('#new_revision_notify');
    if (jQuery(this).attr('checked'))
    {
        new_revision_notify.hide();
        alert('Your change will apply to all pages using this template.');
    }
    else
    {
        if (new_revision_notify.size())
        {
            new_revision_notify.show();
        }
    }
});
";
$cs->registerScript(__CLASS__.'#Notify', $script);

$script = "
jQuery.duplicate = function(me){
    var parent = jQuery(me).parents('.row').first();
    var duplicated = parent.clone();
    jQuery.each(jQuery('input', duplicated), function(){
        jQuery(this).val('');
    });
    
    jQuery('a[class*=\"_trigger\"]', duplicated).text('Select File');
    jQuery('a[class*=\"_remove\"]', duplicated).remove();
    
    parent.after(duplicated);
    
    var container = jQuery(me).parents('.files').first();    
    
    return false;
}

jQuery.remove = function(me){
    var container = jQuery(me).parents('.files').first();
    
    if (jQuery('.row', container).length <= 1) {
        jQuery(me).siblings('input').val('')
            .next('a').html('Select File');
    }
    else
    {    
        jQuery(me).parents('.row').first().remove();
    }    
    
    return false;
}
";
$cs->registerScript(__CLASS__.'#Duplicate', $script);

$script="
if(jQuery('div.row input#Template_masterLayout').attr('checked'))
{
    jQuery('div#parent_drop.row ').next().append('<input id=\"TemplateContent_parent_id\" type=\"hidden\" name=\"TemplateContent[parent_id]\" value=\"1\">');
        jQuery('div#parent_drop.row ').hide();
}
jQuery('div.row input#Template_masterLayout').bind('click',function(){
    if($(this).attr('checked')){
        jQuery('div#parent_drop.row ').next().append('<input id=\"TemplateContent_parent_id\" type=\"hidden\" name=\"TemplateContent[parent_id]\" value=\"0\">');
        jQuery('div#parent_drop.row ').hide();
    }
    else
    {
        jQuery('div#parent_drop.row ').show();
        jQuery('div#parent_drop.row ').next().empty();
    }
});

";
cs()->registerScript(__CLASS__.'#check-master-layout',$script);

if ($model->isNewRecord == false){
    $script = "
jQuery('#revision_id').live('change', function(){
    var id = {$model->id};
    var revision_id = jQuery(this).val();
    window.location = decodeURIComponent(jQuery.param.querystring('".$this->createAbsoluteUrl('/Cms/admin/template/update')."', {'id' : id, 'revision_id' : revision_id}));
});
";
    $cs->registerScript(__CLASS__.'#ChangeRevision', $script);
    $cs->registerCoreScript('bbq');
}

$script = "
jQuery.fn.updateContainer = function(){
    var data = {};
    jQuery('.connectedSortable').each(function(){
        var container = jQuery(this).attr('id').replace('list-container-', '');
        data[container] = [];
        var query = jQuery(this).sortable('serialize');
        if (query.length)
        {
            data[container] = jQuery.deparam.querystring(query).items;
        }
    });
    data = jQuery.param.querystring('', data);
    jQuery('#containers').val(data);
}
setTimeout(function(){jQuery.fn.updateContainer();}, 500);
jQuery('.sort-handle .empty').each(function(){
    jQuery(this).closest('li.sortable').remove();
});
jQuery('.connectedSortable .disabled').each(function(){
    jQuery(this).closest('li.sortable').addClass('disabled');
});
";
$cs->registerScript(__CLASS__.'#UpdateContainer', $script);
$script = "
jQuery.fn.get_page_widget_id = function(obj)
{
    if (jQuery(obj).size())
        return parseInt(jQuery(obj).closest('li.sortable').attr('id').replace('id-', ''));
    return 0;
}
jQuery('#content').delegate('.page_delete', 'click', function(){
    var page_widget_id = jQuery(this).closest('.sortable').attr('id').replace('items_', '');
    if (!confirm('Are you sure you want to remove ?'))
        return false;
    jQuery(this).closest('li.sortable').remove();
    jQuery.fn.updateContainer();
    return false;
});
jQuery('#content').delegate('.sub_page', 'click', function(){
    var params = {};
    var page_widget_id = jQuery(this).closest('.sortable').attr('id').replace('items_', '');
    if (page_widget_id.indexOf('.static') === false)
        params = {'page_widget_id' : page_widget_id};
    else
        params = {'widget_id' : widget_id};
    var url = jQuery.param.querystring(jQuery(this).attr('href'), params);
    window.location = url;
    return false;
});
jQuery('#content').delegate('.add_widget', 'click', function(){
    alert('Add widget to below this');
    return false;
    var container = jQuery(this).closest('.page_tree').attr('id').replace('list-container-', '');
    var url = jQuery.param.querystring(jQuery(this).attr('href'), {'container' : container, 'template_content_id' : 0});
    window.location = url;
    return false;
});
jQuery('#content').delegate('.change_layout', 'click', function(){
    alert('Change widget layout');
    return false;
    var page_widget_id = jQuery(this).closest('.sortable').attr('id').replace('items_', '');
    var url = jQuery.param.querystring(jQuery(this).attr('href'), {'page_widget_id' : page_widget_id});
    window.location = url;
    return false;
});
jQuery('#content').delegate('.duplicate', 'click', function(){
    alert('Duplicate widget');
    return false;
    var page_widget_id = jQuery(this).closest('.sortable').attr('id').replace('items_', '');
    var url = jQuery.param.querystring(jQuery(this).attr('href'), {'page_widget_id' : page_widget_id});
    jQuery.get(url, function(){
        window.location = window.location.href.replace(/\#.*/, '');
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#WidgetActions', $script, CClientScript::POS_READY);
if (Yii::app()->request->getQuery('layout', false) === false)
{
    $cs->registerScriptFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.pack.js');
    $cs->registerCssFile(Yii::app()->theme->baseUrl.'/scripts/fancybox/jquery.fancybox-1.3.4.css');
    $cs->registerCoreScript('bbq');
    $cs->registerScript('PopupLink', "
jQuery('#content').undelegate('.sub_page', 'click');
$('.container').delegate('.ui-tabs-panel h2 a, .page_tree .sub_page', 'click', function(){
    if ($(this).hasClass('sub_page'))
    {
        alert('Edit widget content');
        return false;
    }
    var href = $.param.querystring($(this).attr('href'), {layout: 'popup'});
    if ($(this).hasClass('sub_page'))
    {
        var page_widget_id = jQuery(this).closest('.sortable').attr('id').replace('items_', '');
        href = jQuery.param.querystring(href, {'page_widget_id' : page_widget_id});
    }
    $.fancybox({
        type: 'iframe',
        href: href,
        width: '100%',
        height: '100%',
        showCloseButton: true,
        hideOnOverlayClick: false,
        autoScale: false,
        titleShow: false,
        onClosed: function(){window.location = window.location.href.replace(/\#.*/, '');}
    });
    return false;
});
");
}

if (is_object($page))
{
    $this->breadcrumbs=array($page->title=>array('/Cms/admin/page/update', 'id'=>$page->id));
}
else
{
    $this->breadcrumbs=array('Templates'=>array('index'));
}

if ($model->id)
    $this->breadcrumbs = CMap::mergeArray($this->breadcrumbs, array($model->name=>array('update','id'=>$model->id),'Update'));
else
    $this->breadcrumbs[] = 'Create';
?>

<h1><?php echo ($model->id) ? 'Edit' : 'Create';?> Template <?php echo $model->name; ?></h1>

<style type="text/css">
.CodeMirror-line-numbers {
    width: 2.2em;
    color: #aaa;
    background-color: #eee;
    text-align: right;
    padding-right: .3em;
    font-size: 10pt;
    font-family: monospace;
    padding-top: .4em;
    line-height: normal;
}
</style>

<div class="form wide">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'template-form',
    //'enableClientValidation'=>true,
    //'enableAjaxValidation'=>true,
    //'clientOptions'=>array('validateOnSubmit'=>true),
)); ?>

	<?php //echo $form->errorSummary($model); ?>
	<?php //echo $form->errorSummary($model->currentRevision); ?>

    <?php 
    	if (! $model->IsNewRecord) {
    		echo $form->hiddenField($model, "id"); 
    		echo $form->hiddenField($model->currentRevision,'revision_id');
    		echo $form->hiddenField($model->currentRevision, "id"); 
		}
    ?>
    
    <?php
        $tabs = array(
            'Content'=>$this->renderPartial('_content', array(
                'model'=>$model,
                'form'=>$form,
                'revisions'=>$revisions,
                'page'=>$page,
                'childrenTemplates'=>$childrenTemplates,
                'canDelete'=>!count($pages)), true),
            'JS & CSS'.($model->id ? ' for Rev#'.$model->currentRevision->revision_id : '')=>$this->renderPartial('_files', array(
                'model'=>$model,
                'form'=>$form), true),
        );
        if ($model->isNewRecord == false)
        {
            
            $tabs['Content Structure'] = $this->renderPartial('_structure',array('model'=>$model->currentRevision, 'containers'=>$containers), true);
            $title = 'Pages '.($model->id ? ' using Rev#'.$model->currentRevision->revision_id : '');
            $tabs[$title] = (count($pages) ? $this->widget('zii.widgets.CMenu', array('items'=>$pages), true) : '<p>Not used in any page.</p>');
        }
        $this->widget('zii.widgets.jui.CJuiTabs', array(
            'id'=>'template-tabs',
            'tabs'=>$tabs,
            'options'=>array(
                'cookie'=>array('expires'=>30),
            ),
        ));
        $script = "
        jQuery('#template-tabs').bind('tabsselect', function(event, ui){
            if (ui.index == 3)
            {
                jQuery('.form_items').hide();
            }
            else
            {
                jQuery('.form_items').show();
            }
        });
        ";
        Yii::app()->clientScript->registerScript(__CLASS__.'#InfoTab', $script);
    ?>
    
    <div class="row form_items">
        <?php echo $form->labelEx($model,'status', array('label'=>'Active')); ?>
        <?php echo $form->checkBox($model,'status'); ?>
        <?php echo $form->error($model,'status'); ?>
    </div>

    <?php if ($model->isNewRecord == false):?>
    <div class="row form_items">
        <?php echo $form->labelEx($model,'creation_datetime'); ?>
        <?php echo Yii::app()->getDateFormatter()->formatDateTime(strtotime($model->creation_datetime)); ?>
    </div>

    <div class="row form_items">
        <?php echo $form->labelEx($model,'last_update'); ?>
        <?php echo Yii::app()->getDateFormatter()->formatDateTime(strtotime($model->last_update)); ?>
    </div>
    <?php endif;?>

    <?php if ($model->isNewRecord == false):?>
    <div class="row form_items">
        <label>&nbsp;</label>
        <?php echo CHtml::checkBox('same_revision', false); ?>
        <label for="same_revision" style="float:none;width: auto;text-align:left; display:inline">Check this box to not generate new revision of this template.</label>
    </div>
    <?php endif;?>
    <div class="row form_items log_message">
        <?php echo $form->labelEx($model->currentRevision,'log'); ?>
        <?php echo $form->textArea($model->currentRevision, 'log', array('cols'=>70, 'rows'=>3)); ?>
        <?php echo $form->error($model->currentRevision,'log'); ?>
    </div>

    <div class="row buttons form_items">
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
        <?php if ($model->isNewRecord == false && is_object($page)):?>
        <strong id="new_revision_notify">A new revision will be created and applied for <?php echo CHtml::encode($page->title);?></strong>
        <?php endif;?>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->